/*
 * Semaphore file that initializes the 100 semaphores
 * 
 * semaphore.c
 */

#include <stdio.h>
#include <stdlib.h>
#include "semaphore.h"

/*
 * Initiate the semaphores.
 */
void initiateSemaphores(SEMAPHORES *semaphores)
{
    int i, j;
    for(i = 0 ; i < 100 ; i++){
        semaphores -> state[i] = 1;
         for(j = 0 ; j < 10 ; j++){
            semaphores -> queue[i][j] = -1;
        }
    }
    
   
    
    semaphores -> in = 0;
    semaphores -> out = 0;
}

/*
 * Check if any process is waiting
 */
int anyWaiting(SEMAPHORES *semaphores, int semaphore)
{
    int i;
    for(i=0 ; i < 10 ; i++)
    {
        // If there is a process waiting, return 1
        if(semaphores -> queue[semaphore][i] != -1) {
            return 1;
        }
    }
    
    return 0;
}

/*
 * Check if a specific process is waiting
 */
int isWaiting(SEMAPHORES *semaphores, int semaphore, int process)
{
    int i;
    for(i=0 ; i < 10 ; i++)
    {
        // If the process waiting, return 1
        if(semaphores -> queue[semaphore][i] == process) {
            return 1;
        }
    }
    
    return 0;
}


/****** STACK METHODS ******/

/*
 * Push a process onto the semaphore wait queue.
 */
void pushProcess(SEMAPHORES *stack, int semaphore, int item)
{
    stack->queue[semaphore][stack->in++] = item;
    if(stack->in >= 10)
        stack-> in = 0;
}

/*
 * Pop the last process off the semaphore wait queue,
 * allowing them to access shared storage on the next
 * time slice.
 */
int popProcess(SEMAPHORES *stack, int semaphore)
{
    int ready = stack -> queue[semaphore][stack -> out];
    stack -> queue[semaphore][stack -> out] = -1;
    stack -> out++;
    if(stack->out >= 10)
        stack-> out = 0;
    return ready;
}